package com.cdinternationalcompany.syhapp

import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.Handler
import android.util.Base64
import android.util.Log

import com.cdinternationalcompany.syhapp.push.ManufacturerHelper
import com.cdinternationalcompany.syhapp.push.TokenObserver
import com.cdinternationalcompany.syhapp.push.TokenObserver.Companion
import com.cdinternationalcompany.syhapp.utils.ChannelManager
//import com.cd.games.university.app.utils.TobiasPlugin
import com.heytap.msp.push.HeytapPushManager
import com.xiaomi.mipush.sdk.MiPushClient
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.renderer.FlutterUiDisplayListener

import java.security.MessageDigest


class MainActivity : FlutterActivity() {

    private val mHandler = Handler()

    companion object {
        private val TAG = MainActivity::class.java.simpleName
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        CustomPluginRegist.registerWith();
//        TobiasPlugin.registerWith(flutterEngine);
//        TobiasPlugin.registerWith(this.registrarFor("com.jarvan.tobias.TobiasPlugin"));
        ChannelManager.instance.initChannel(flutterEngine?.dartExecutor, this,this.contentResolver)



//[B@76d1c5
        ChannelManager.instance.apply {
//            on(ResourceApi.REQUEST_METHOD, ResourceApi(this@MainActivity))
//            on(WeChatLoginApi.REQUEST_METHOD, WeChatLoginApi(this@MainActivity))
//            on(WebApi.REQUEST_METHOD, WebApi(this@MainActivity))
//            on(VideoDetailApi.REQUEST_METHOD, VideoDetailApi(this@MainActivity))
//            on(ArticleDetailApi.REQUEST_METHOD, ArticleDetailApi(this@MainActivity))
        }
        if (BuildConfig.DEBUG) {
            try {
                val info = packageManager.getPackageInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_SIGNATURES)
                for (each in info.signatures) {
                    val md = MessageDigest.getInstance("SHA")
                    md.update(each.toByteArray())
                    Log.d(TAG, Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
            } catch (exception: Exception) {
                exception.printStackTrace()
            }
        }
        flutterEngine?.renderer?.addIsDisplayingFlutterUiListener(object : FlutterUiDisplayListener {
            override fun onFlutterUiDisplayed() {
                Log.d("MainActivity", "onFlutterUiDisplayed")
                openNotificationIfNeeded(intent)
            }
            override fun onFlutterUiNoLongerDisplayed() {
                Log.d("MainActivity", "onFlutterUiNoLongerDisplayed")
            }

        })
        if (ManufacturerHelper.isOPPO()) {
            HeytapPushManager.requestNotificationPermission();
        }
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        openNotificationIfNeeded(intent)
    }

    private fun openNotificationIfNeeded(intent: Intent) {
        if (intent == null) {
            return
        }
        val bundle = intent.extras
        if (bundle != null) {
            if (bundle.keySet().contains("jump_target")) {
                val para = mutableMapOf<String,String>()
                for (key in bundle.keySet()) {
                    val content = bundle.getString(key)
                    para[key] = content.toString()
                    Log.i(MainActivity.TAG, "receive data from push, key = $key, content = $content")
                }
                if (ChannelManager.instance.mEventSink != null) {
                    ChannelManager.instance.callFlutter(
                        "PushApi/receiveMessage", para,
                    )
                    intent.removeExtra("jump_target")
                } else {
                    mHandler.postDelayed({
//                    TokenObserver.instance.collectionToken(context)
                        ChannelManager.instance.callFlutter(
                            "PushApi/receiveMessage", para,
                        )
                        bundle.clear()
                        intent.removeExtra("jump_target")
                    }, 6000)

                }


            }
        }
//        val extras = intent.getStringExtra("extras")
//        if (TextUtils.isEmpty(extras)) {
//            return
//        }
//        try {
//            extras?.let {
//                ChannelManager.instance.callFlutter(
//                        "PushApi/receiveMessage", it,
//                )
//            }
//        } catch (e: Exception) {
//            e.printStackTrace()
//        }
    }
}
